package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.search.result.SearchResultCount;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.dict.entity.Dict;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.oa.core.entity.com.Person;
import com.fz.us.oa.core.entity.com.Resident;
import com.fz.us.oa.core.service.com.*;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by dzw on 2018/3/15.
 * 统计明细功能
 */
@Controller
@RequestMapping("/com/detail")
public class DetailController extends BaseController {
    private static final long serialVersionUID = 2467605921062875575L;

    @Autowired
    private PersonService personService;
    @Autowired
    private ResidentService residentService;
    @Autowired
    private StudyService studyService;
    @Autowired
    private WorkService workService;
    @Autowired
    private FamilyService familyService;

    //获取备选书记系统字典
    public DictItem beiXuan(){
        DictItem beixuan = null;
        Dict personNature = dictService.getByValue("personNature");
        if(personNature!=null){
            beixuan = dictItemService.getByValue(personNature.getId(), "shujihoubei");
        }
        return beixuan;
    }

    /**
     * 学历-全区 （也是统计明细的首页） （streetId不为空的话就是 学历-街道）
     */
    @RequestMapping(value = "eduAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String eduAll(@CurrentUser User user, Model model, String streetId){
        DictItem generalAfter = getGeneralAfter();
        DecimalFormat df = new DecimalFormat("0.00%");
        List<DictItem> eduList = getDictItems(user, "edu");

        List<Map<String, Object>> list0 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>();

        Map<String, Object> rMap;

        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        int allCount = personService.findPerson(rules).size();//所有人数
        BigDecimal allCountB = new BigDecimal(allCount);

        int beixuan = personService.getBeiXuanCount(true, beiXuan(), generalAfter); //备选人数
        int juminqu = personService.getBeiXuanCount(false, beiXuan(), generalAfter); //居民区人数
        BigDecimal beiXuanCount = new BigDecimal(beixuan);
        BigDecimal juMinQuCount = new BigDecimal(juminqu);

        //居民区书记
        for(DictItem edu:eduList){
            rMap = new HashMap<String, Object>();
            int count = 0;
            if(StringUtils.isEmpty(streetId)){
                count = personService.getCountEduAll(false,beiXuan(),edu, generalAfter);
            }else{
                count = personService.getCountEduAll(false,beiXuan(),edu,dictItemService.get(streetId), generalAfter);
            }

            rMap.put("eduName", edu.getName());
            rMap.put("personCount", count);
            if(juminqu!=0){
                rMap.put("bili", df.format(new BigDecimal(count).divide(juMinQuCount,2,BigDecimal.ROUND_UP)));
            }else{
                rMap.put("bili", "0%");
            }

            list0.add(rMap);
        }

        //备选书记
        for(DictItem edu:eduList){
            rMap = new HashMap<String, Object>();
            int count = 0;
            if(StringUtils.isEmpty(streetId)){
                count = personService.getCountEduAll(true,beiXuan(),edu, generalAfter);
            }else{
                count = personService.getCountEduAll(true,beiXuan(),edu,dictItemService.get(streetId), generalAfter);
            }
            rMap.put("eduName", edu.getName());
            rMap.put("personCount", count);
            if(beixuan!=0){
                rMap.put("bili", df.format(new BigDecimal(count).divide(beiXuanCount,2,BigDecimal.ROUND_UP)));
            }else{
                rMap.put("bili", "0%");
            }
            list1.add(rMap);
        }

        //小计
        for(DictItem edu:eduList){
            rMap = new HashMap<String, Object>();
            int count = 0;
            if(StringUtils.isEmpty(streetId)){
                count = personService.getCountEduAll(edu, generalAfter);
            }else{
                count = personService.getCountEduAll(edu,dictItemService.get(streetId), generalAfter);
            }
            rMap.put("eduName", edu.getName());
            rMap.put("personCount", count);
            if(allCount!=0){
                rMap.put("bili", df.format(new BigDecimal(count).divide(allCountB,2,BigDecimal.ROUND_UP)));
            }else{
                rMap.put("bili", "0%");
            }
            list3.add(rMap);
        }

        model.addAttribute("list0", list0);
        model.addAttribute("list1", list1);
        model.addAttribute("list3", list3);
        model.addAttribute("num", allCount);

        List<DictItem> streetList = getDictItems(user, "street");
        if(streetList.size()>0){
            model.addAttribute("firstStreetId", streetList.get(0).getId());
        }

        if(StringUtils.isEmpty(streetId)){
            return "/det/edu_all";
        }else{
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/det/edu_street";
        }

    }

    /**
     * 性别年龄-全区  （如果streetId不为空，那就是年龄性别-街道）
     */
    @RequestMapping(value = "ageAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String ageAll(@CurrentUser User user, Model model, String streetId){
        DecimalFormat df = new DecimalFormat("0.00%");
        DictItem generalAfter = getGeneralAfter();

        List<Rule> rules0 = new ArrayList<Rule>();
        rules0.add(RuleHelper.ne("personNature", beiXuan()));
        rules0.add(RuleHelper.eq("gender", "男"));
        rules0.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules0.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules0.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nan2 = personService.findCountBySearch(rules0).getCount(); //居民区书记男人数

        List<Rule> rules1 = new ArrayList<Rule>();
        rules1.add(RuleHelper.ne("personNature", beiXuan()));
        rules1.add(RuleHelper.eq("gender", "女"));
        rules1.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules1.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules1.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nv2 = personService.findCountBySearch(rules1).getCount(); //居民区书记女人数

        List<Rule> rules3 = new ArrayList<Rule>();
        rules3.add(RuleHelper.eq("personNature", beiXuan()));
        rules3.add(RuleHelper.eq("gender", "男"));
        rules3.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules3.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules3.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nan1 = personService.findCountBySearch(rules3).getCount(); //备选书记男人数

        List<Rule> rules4 = new ArrayList<Rule>();
        rules4.add(RuleHelper.eq("personNature", beiXuan()));
        rules4.add(RuleHelper.eq("gender", "女"));
        rules4.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules4.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules4.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nv1 = personService.findCountBySearch(rules4).getCount(); //备选书记女人数

        List<Rule> rules5 = new ArrayList<Rule>();
        rules5.add(RuleHelper.eq("gender", "男"));
        rules5.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules5.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules5.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nan0 = personService.findCountBySearch(rules5).getCount(); //合计男人数

        List<Rule> rules6 = new ArrayList<Rule>();
        rules6.add(RuleHelper.eq("gender", "女"));
        rules6.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules6.add(RuleHelper.eq("generalDict", generalAfter));
        if(StringUtils.isNotEmpty(streetId)){
            rules6.add(RuleHelper.eq("street", dictItemService.get(streetId)));
        }
        Long nv0 = personService.findCountBySearch(rules6).getCount(); //合计女人数

        int age1 = 0;
        int age2 = 0;
        int age0 = 0;

//        int beixuan = personService.getBeiXuanCount(true, beiXuan());
//        int juminqu = personService.getBeiXuanCount(false, beiXuan());
        int beixuan = Integer.parseInt(nan1.toString())+Integer.parseInt(nv1.toString());
        int juminqu = Integer.parseInt(nan2.toString())+Integer.parseInt(nv2.toString());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(streetId)){
            params.put("street", dictItemService.get(streetId));
        }
        List<Person> personList = personService.getList(params); //当前总人数
        for(Person person:personList){
            int thisAge = getAge(person);
            age0+=thisAge;
            if("shujihoubei".equals(person.getPersonNature()==null?"":person.getPersonNature().getValue())){
                age1+=thisAge;
            }else{
                age2+=thisAge;
            }
        }

        BigDecimal ageB1 = new BigDecimal(age1);
        BigDecimal ageB2 = new BigDecimal(age2);
        BigDecimal ageB0 = new BigDecimal(age0);

        BigDecimal countB1 = new BigDecimal(beixuan); //备选总人数
        BigDecimal countB2 = new BigDecimal(juminqu); //居民区总人数
        BigDecimal countB0 = new BigDecimal(personList.size()); //当前总人数

        model.addAttribute("nan0", nan0);
        model.addAttribute("nan1", nan1);
        model.addAttribute("nan2", nan2);
        model.addAttribute("nv0", nv0);
        model.addAttribute("nv1", nv1);
        model.addAttribute("nv2", nv2);

        model.addAttribute("avgAge0", personList.size()==0 ? 0 : ageB0.divide(countB0,2,BigDecimal.ROUND_UP));
        model.addAttribute("avgAge1", beixuan==0 ? 0 : ageB1.divide(countB1,2,BigDecimal.ROUND_UP));
        model.addAttribute("avgAge2", juminqu==0 ? 0 : ageB2.divide(countB2,2,BigDecimal.ROUND_UP));


        BigDecimal beiXuanCount = new BigDecimal(beixuan);
        BigDecimal juMinQuCount = new BigDecimal(juminqu);
        model.addAttribute("nan2Bili", juminqu==0 ? "0%" : df.format(new BigDecimal(nan2).divide(juMinQuCount,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nv2Bili", juminqu==0 ? "0%" : df.format(new BigDecimal(nv2).divide(juMinQuCount,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nan1Bili", beixuan==0 ? "0%" : df.format(new BigDecimal(nan1).divide(beiXuanCount,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nv1Bili", beixuan==0 ? "0%" : df.format(new BigDecimal(nv1).divide(beiXuanCount,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nan0Bili", personList.size()==0 ? "0%" : df.format(new BigDecimal(nan0).divide(countB0,2,BigDecimal.ROUND_UP)));
        model.addAttribute("nv0Bili", personList.size()==0 ? "0%" : df.format(new BigDecimal(nv0).divide(countB0,2,BigDecimal.ROUND_UP)));

        if(StringUtils.isEmpty(streetId)){
            return "/det/age_all";
        }else{
            List<DictItem> streetList = getDictItems(user, "street");
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/det/age_street";
        }

    }

    /**
     * 人员性质-全区 （如果streetId不为空，那就是 人员性质-街道）
     */
    @RequestMapping(value = "personNatureAll", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String personNatureAll(@CurrentUser User user, Model model, String streetId){
        DecimalFormat df = new DecimalFormat("0.00%");
        DictItem generalAfter = getGeneralAfter();

        DictItem street = null;
        if(StringUtils.isNotEmpty(streetId)){
            street = dictItemService.get(streetId);
        }

        int allCount = 0;
        if(street==null){
            allCount = personService.getAllCount(generalAfter);
        }else{
            allCount = personService.getCountByStreet(street, generalAfter);
        }
        model.addAttribute("allCount", allCount);

        BigDecimal allCountB = new BigDecimal(allCount);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> rMap;

        List<DictItem> personNature = getDictItems(user, "personNature");
        for(DictItem nature:personNature){
            rMap = new HashMap<String, Object>();
            int count = 0;
            if(street==null){
                count = personService.getCountByPersonNature(nature,generalAfter);
            }else{
                count = personService.getCountByNatureAndStreet(nature, street, generalAfter);
            }

            if("shujihoubei".equals(nature.getValue())){
                model.addAttribute("beiXuanCount", count);
            }else{
                rMap.put("natureName", nature.getName());
                rMap.put("natureCount", count);
                rMap.put("bili", allCount==0 ? "0%" : df.format(new BigDecimal(count).divide(allCountB,2,BigDecimal.ROUND_UP)));
                list.add(rMap);
            }
        }
        model.addAttribute("list", list);

        //如果是街道，要有 换届应调整人数
        if(street!=null){
            Dict xingzhi = dictService.getByValue("personNature");
            DictItem tuixiufanpin = null;
            if(xingzhi!=null){
                tuixiufanpin = dictItemService.getByValue(xingzhi.getId(),"tuixiufanpin");
            }

            List<Resident> residentList = residentService.getResidentByStreet(street);
            int fanPinCount = personService.getHuanJieCountByStreet(street, tuixiufanpin, generalAfter).size();
            int juMinQuCount = residentList.size();
            BigDecimal aB = new BigDecimal(juMinQuCount).multiply(new BigDecimal(0.3));
            BigDecimal re = new BigDecimal(fanPinCount).subtract(aB);
            BigDecimal reC = re.setScale(0, BigDecimal.ROUND_UP);
            int huan = Integer.parseInt(reC.toString());
            model.addAttribute("huanjieCount", huan<0?"0":huan);
        }

        if(StringUtils.isEmpty(streetId)){
            return "/det/person_nature_all";
        }else{
            List<DictItem> streetList = getDictItems(user, "street");
            model.addAttribute("streetList", streetList);
            model.addAttribute("selectStreetId", streetId);
            return "/det/person_nature_street";
        }

    }







    //获取一个人的年龄
    public int getAge(Person person){
        int userYear = Integer.parseInt(DataUtil.DateToString(person.getBirthday(), "yyyy"));
        int thisYear = Integer.parseInt(DataUtil.DateToString(new Date(), "yyyy"));
        return thisYear-userYear;
    }

}

